// 创建右键菜单
chrome.runtime.onInstalled.addListener(() => {
    chrome.contextMenus.create({
        id: 'openMonitor',
        title: '打开 拦截响应',
        contexts: ['action']  // 只在扩展图标的右键菜单中显示
    });
    // 初始化截图功能的开关状态
    chrome.storage.local.get(['screenshotEnabled'], function(result) {
        if (result.screenshotEnabled === undefined) {
            chrome.storage.local.set({ screenshotEnabled: true });
        }
    });
});

// 截图功能
async function captureAndSaveScreenshot(tab) {
    return new Promise((resolve, reject) => {
        chrome.tabs.captureVisibleTab(
            tab.windowId,
            {format: 'png'},
            function(dataUrl) {
                if (chrome.runtime.lastError) {
                    console.error('Screenshot error:', chrome.runtime.lastError.message);
                    reject(chrome.runtime.lastError);
                    return;
                }
                
                try {
                    // 生成文件名
                    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
                    const url = new URL(tab.url);
                    // 包含端口号和hash的处理
                    const urlPath = (url.pathname + url.hash).replace(/[/#]/g, '_') || 'root';
                    const filename = `localhost${url.port ? '_' + url.port : ''}${urlPath}_${timestamp}.png`;

                    // 直接使用dataUrl下载
                    chrome.downloads.download({
                        url: dataUrl,
                        filename: filename,
                        saveAs: false
                    }, (downloadId) => {
                        if (chrome.runtime.lastError) {
                            console.error('Download error:', chrome.runtime.lastError.message);
                            reject(chrome.runtime.lastError);
                        } else {
                            resolve(downloadId);
                        }
                    });
                } catch (error) {
                    console.error('Processing error:', error);
                    reject(error);
                }
            }
        );
    });
}

// 处理右键菜单点击
chrome.contextMenus.onClicked.addListener((info, tab) => {
    if (info.menuItemId === 'openMonitor') {
        chrome.tabs.create({
            url: chrome.runtime.getURL('monitor.html')
        });
    }
});

// 监听来自 content script 的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'saveRequest') {
        chrome.storage.local.get(['ajaxRequests'], function(result) {
            const requests = result.ajaxRequests || [];
            requests.unshift(message.data);
            
            // 最多保存100条记录
            if (requests.length > 100) {
                requests.pop();
            }
            
            chrome.storage.local.set({ ajaxRequests: requests });
        });
    }
    
    if (message.type === 'GET_TAB_INFO') {
        // 确保sender.tab存在
        if (!sender.tab) {
            sendResponse({
                id: 'unknown',
                title: 'Unknown Tab',
                url: ''
            });
            return true;
        }

        // 返回当前标签页信息
        sendResponse({
            id: sender.tab.id,
            title: sender.tab.title || 'Unknown Tab',
            url: sender.tab.url || ''
        });
        return true;
    }

    // 处理立即截图请求
    if (message.type === 'TAKE_SCREENSHOT_NOW') {
        chrome.tabs.query({active: true, currentWindow: true}, async function(tabs) {
            if (tabs[0] && tabs[0].url && tabs[0].url.match(/^https?:\/\/localhost(:\d+)?/)) {
                try {
                    await captureAndSaveScreenshot(tabs[0]);
                    sendResponse({ success: true });
                } catch (error) {
                    console.error('Immediate screenshot failed:', error);
                    sendResponse({ success: false, error: error.message });
                }
            } else {
                sendResponse({ success: false, error: 'Current tab is not a localhost page' });
            }
        });
        return true; // 保持消息通道打开以支持异步响应
    }
});

// 监听URL变化
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    // 检查截图功能是否启用
    chrome.storage.local.get(['screenshotEnabled'], async function(result) {
        if (!result.screenshotEnabled) {
            return;
        }
        
        // 只处理localhost的URL变化，并且只在页面加载完成时截图
        if (changeInfo.status === 'complete' && tab.url && tab.url.match(/^https?:\/\/localhost(:\d+)?/)) {
            // 等待一小段时间确保页面完全渲染
            setTimeout(async () => {
                try {
                    await captureAndSaveScreenshot(tab);
                } catch (error) {
                    console.error('Screenshot failed:', error);
                }
            }, 1000); // 等待1秒确保页面渲染完成
        }
    });
}); 